.MODEL small
endlM macro			; spring naar begin volgende lijn
	mov ah, 2
	mov dl, 0Ah		; nieuwe lijn
	int 21h
	mov ah, 2		; keer terug naar begin lijn
	mov dl, 0Dh
	int 21h
endm

.STACK 1024
.DATA
	rand dw ?
	bereik dw 10
	powersoften dw 10000, 1000, 100, 10, 1
.CODE
.STARTUP
	xor ah, ah		; randomize
		int 1Ah
		mov rand, dx
main:
	push bereik		; bereik van random
	call randint
	push ax
	call printuint
	mov ah, 7		; lees karakter zonder echo
		int 21h
	cmp al, 27		; esc (ascii 27) sluit af
	endlM
	jne main	
.EXIT

randint proc near
    push bp			; save dynamic link
    mov bp,sp		; update bp
	push bx			; save context
		push cx
		push dx
	mov bx, [bp+4]	; 2 words terug, dus naar bereik
	mov ax, rand
	mov dx, 16333
	mul dx
	add ax, 25887
	and ax, 7FFFh
	mov rand, ax
	mul bx			; herschalen naar [0, bereik[
		mov cx, 32768
		div cx
	pop dx			; restore context
		pop cx
		pop bx
    pop bp			; restore bp
    ret 2			; return freeing param from stack (2 bytes)
randint endp

;print an unsigned integer to stdout
;value on tos (16-bit 2's compl)
printuint proc near	; near procedure
    ;save dynamic link
    push bp
    ;update bp
    mov bp,sp
    ;save context
    push ax
    push bx
    push dx
    push si
    ;load param in bx
    mov bx,[bp+4] ;near proc, one word return address
    ;handle special case of zero
    test bx,0FFFFh
    jnz printint_nonzero
    mov ah,02h
    mov dl,'0'
    int 21h
    jmp printint_done
printint_nonzero:
    ;determine largest power of ten smaller than bx
    ;init si to point to first element of powersoften array
    mov si,offset powersoften
    ; while bx<[si] increment si C: while(bx<powersoften[si]) si++
printint_nextpoweroften:
    cmp bx,[si]
    jae printint_powerfound
    add si,2    
    jmp printint_nextpoweroften
printint_powerfound:
    ;ok now print digits
    mov ax,bx
    xor dx,dx  ;extend to DX:AX (32-bit), unsigned, so zero
    div word ptr [si]  ;divide DX:AX by current power of ten, result in AX, remainder in DX
    mov bx,dx  ;move remainder to bx
    mov ah,02h ;print al
    mov dl,al
    ;add 48 to convert to ascii
    add dl,48
    int 21h
    ;was this the last digit? i.e. [si]==1
    cmp word ptr [si],1
    je printint_done
    add si,2   ;increment si
    jmp printint_powerfound ;repeat for next digit
printint_done:
    ;restore context
    pop si
    pop dx
    pop bx
    pop ax
    ;restore bp
    pop bp
    ;return freeing param from stack (2 bytes)
    ret 2
printuint endp
end